package leetcode.f1t100;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 合并区间
 * https://leetcode.com/problems/merge-intervals/
 *
 * @Author lichongxiao
 * @Date 2022/10/25 10:56
 */
public class Q56_MergeIntervals {
    public int[][] merge(int[][] intervals) {
        List<int[]> ansList = new ArrayList<>();
        Arrays.sort(intervals, (o1, o2) -> {
            if (o1[0] == o2[0]) {
                return o1[1] - o2[1];
            }
            return o1[0] - o2[0];
        });
        int begin = intervals[0][0], end = intervals[0][1];
        for (int[] interval : intervals) {
            if (interval[0] == begin || interval[0] <= end) {
                end = interval[1] > end ? interval[1] : end;
            } else {
                ansList.add(new int[]{begin,end});
                begin = interval[0];
                end = interval[1];
            }
        }
        ansList.add(new int[]{begin,end});
        return ansList.toArray(new int[0][]);
    }

    public static void main(String[] args) {
        Q56_MergeIntervals bean = new Q56_MergeIntervals();
        int[][] merge = bean.merge(new int[][]{{1, 3}, {1, 2}, {2, 3}});
        for (int[] interval : merge) {
            for(int num : interval){
                System.out.print(num+" ");
            }
            System.out.println();
        }
    }
}
